package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Ronaldo
 * @date 2021/8/1
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    private static final String LOGIN_PATH = "/login/in";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求及响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.获取请求路径
        String path = request.getURI().getPath();
        log.info("uri {}" + path);

        //3.判断是否为登录路径
        if (StringUtils.isNoneBlank(path) && path.contains(LOGIN_PATH)) {
            //如果是登录请求则直接放行
            return chain.filter(exchange);
        }

        //4.不是登录请求  获取请求头中的token信息
        String token = request.getHeaders().getFirst("token");

        //5.判断token为空则返回401,未认证
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.不为空则校验token
        //获取token的载荷信息
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        //校验token
        int flag = AppJwtUtil.verifyToken(claimsBody);

        try {
            if (flag == -1 || flag == 0) {
                //证明token有效  token有效则设置请求头  放行
                String userId = String.valueOf(claimsBody.get("id"));
                request.mutate().header("userId", userId);
                return chain.filter(exchange);
            } else {
                //token过期   或  被篡改
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
